package controller

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"wish_go/src/main/com/ajie/common"
	"wish_go/src/main/com/ajie/dao"
	"wish_go/src/main/com/ajie/model"
	"wish_go/src/main/com/ajie/result"
	"wish_go/src/main/com/ajie/vo"
)

func PageWish(req *gin.Context) {
	var wv vo.WishVo
	if err := req.BindJSON(&wv); err != nil {
		result.Error(req, 500, "参数解析异常:"+err.Error())
		return
	}
	pagination := common.GeneratePagination(wv.Page)
	rows, total, dbErr := dao.PageWish(&wv.Wish, &pagination)
	if dbErr != nil {
		result.Error(req, 500, "社区心愿获取失败:"+dbErr.Error())
		return
	}
	result.PageRsult(req, rows, total)
}

func InsertWish(req *gin.Context) {
	var wish model.Wish
	if err := req.BindJSON(&wish); err != nil {
		result.Error(req, 500, "参数解析异常:"+err.Error())
		return
	}
	if err := dao.InsertWish(wish); err != nil {
		result.Error(req, 500, "填报异常:"+err.Error())
		return
	}
	result.Success(req, "填报成功")
}

func UpdateWish(req *gin.Context) {
	var wish model.Wish
	if err := req.BindJSON(&wish); err != nil {
		result.Error(req, 500, "参数解析异常:"+err.Error())
		return
	}
	i, dbErr := dao.UpdateWish(wish)
	if dbErr != nil {
		result.Error(req, 500, "填报异常:"+dbErr.Error())
		return
	}
	if i < 1 {
		result.Error(req, 500, "修改失败")
		return
	}
	result.Success(req, "修改成功")
}

func WishHotspot(req *gin.Context) {
	var wish model.Wish
	if err := req.BindJSON(&wish); err != nil {
		result.Error(req, 500, "参数解析异常:"+err.Error())
		return
	}
	i, dbErr := dao.WishHotspot(wish)
	if dbErr != nil {
		result.Error(req, 500, "更新异常:"+dbErr.Error())
		return
	}
	if i < 1 {
		result.Error(req, 500, "修改失败")
		return
	}
	result.Success(req, "修改成功")
}

func DeleteWish(req *gin.Context) {
	id, _ := strconv.Atoi(req.Param("id"))
	// 解析参数为实体json
	if id == 0 {
		result.Error(req, 500, "id不能为空")
		return
	}
	wish := model.Wish{}
	wish.Id = uint(id)
	dao.DeleteWish(wish)
	result.Success(req, "删除成功")
}

func GetAreaByOpenid(req *gin.Context) {
	openid := req.Param("openid")
	// 解析参数为实体json
	if len(openid) == 0 {
		result.Error(req, 500, "openid不能为空")
		return
	}
	rows, dbErr := dao.GetAreaByOpenid(openid)
	if dbErr != nil {
		result.Error(req, 500, "查询异常:"+dbErr.Error())
		return
	}
	result.SuccessData(req, "获取成功", rows)
}
